<template>
    <div class="page-wrap">
        <div class="page-cont" v-loading="loading">
            <div class="page-header" :style="{ height: isCollaspeHeader ? '112px' : 'unset' }">
                <div v-if="lineOptions.length">
                    <div v-if="treeData">
                        <flexbox>
                            <span>产线/产品：</span>
                            <SelectCatalogCode
                                v-model:value="catalogCode"
                                :levelLimit="2"
                                :defaultTreeData="treeData"
                                @change="handleCascaderChange"
                            />
                        </flexbox>
                        <a-divider style="margin: 12px 0" />
                    </div>
                    <div v-if="isCollaspeHeader">
                        <a-tag color="#0176d3">
                            {{ collaspeHeaderTitle }}
                        </a-tag>
                    </div>
                    <div v-else>
                        <flexbox align="flex-start">
                            <div style="width: 60px; height: 22px; padding-top: 2px">产品线：</div>
                            <div style="flex: 1">
                                <flexbox wrap="wrap">
                                    <a-checkable-tag
                                        :checked="checkedLine === index"
                                        v-for="(item, index) of lineOptions"
                                        :key="index"
                                        @change="handleChangeLine($event, index)"
                                        style="margin-bottom: 8px"
                                    >
                                        {{ item.catalogName }}
                                    </a-checkable-tag>
                                </flexbox>
                            </div>
                        </flexbox>

                        <flexbox align="flex-start" class="margin-t-8">
                            <div style="width: 60px;height: 22px padding-top: 2px">产品：</div>
                            <div style="flex: 1">
                                <flexbox wrap="wrap">
                                    <a-checkable-tag
                                        :checked="checkedPro === index"
                                        v-for="(item, index) of proOptions"
                                        :key="index"
                                        @change="handleChangePro($event, index)"
                                        style="margin-bottom: 8px"
                                    >
                                        {{ item.catalogName }}
                                    </a-checkable-tag>
                                </flexbox>
                            </div>
                        </flexbox>

                        <flexbox align="flex-start" class="margin-t-8">
                            <div style="width: 60px; height: 22px; padding-top: 2px">子产品：</div>
                            <div style="flex: 1">
                                <flexbox wrap="wrap">
                                    <a-checkable-tag
                                        :checked="checkedSubPro === index"
                                        v-for="(item, index) of subProOptions"
                                        :key="index"
                                        @change="handleChangeSubPro($event, index)"
                                    >
                                        {{ item.catalogName }}
                                    </a-checkable-tag>
                                </flexbox>
                            </div>
                        </flexbox>
                    </div>

                    <flexbox justify="center" style="position: absolute; bottom: 5px; left: 0; right: 0; width: 100%">
                        <my-icon
                            type="iconbiaotixiala"
                            :rotate="0"
                            style="color: #2359dd"
                            v-if="isCollaspeHeader"
                            @click="handleToggleCollaspeHeader"
                        />
                        <my-icon type="iconbiaotixiala" :rotate="180" style="color: #2359dd" v-else @click="handleToggleCollaspeHeader" />
                    </flexbox>
                </div>
            </div>

            <flexbox
                align="flex-start"
                class="page-cont-versionControl"
                style="flex: 1; background: #fff; margin-top: 12px; padding: 12px 24px 24px 24px; overflow: hidden"
            >
                <div class="left" :style="{ width: leftWidth }" v-if="systemInfo.catalogCode">
                    <VersionTree
                        ref="versionTreeRef"
                        :systemInfo="systemInfo"
                        :proSystemInfo="proSystemInfo"
                        :leftWidth="leftWidth"
                        :systemDetail="systemDetail"
                        :disabled="disabled"
                        @select="handleSelectTree"
                        @checkReleaseChange="getSystemDetail"
                    />
                    <div class="moveBtn" v-move="updateWidth" />
                </div>
                <div :style="{ flex: 1, width: `calc(100% - ${leftWidth})` }" v-if="systemInfo.catalogCode">
                    <VersionInfo
                        :systemInfo="systemInfo"
                        :proSystemInfo="proSystemInfo"
                        :systemDetail="systemDetail"
                        :versionInfo="selectedVersionInfo"
                        :disabled="disabled"
                        @success="handleSuccess"
                    />
                </div>
            </flexbox>
        </div>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { treeFilter } from '@/utils/tree';
import { useRoute } from 'vue-router';
import VersionTree from './components/VersionTree.vue';
import VersionInfo from './components/VersionInfo.vue';
import { SelectCatalogCode } from '@/components';
import { defineComponent, getCurrentInstance, ref, unref, reactive, toRefs, computed, watch, nextTick, onMounted } from 'vue';
export default defineComponent({
    components: {
        VersionTree,
        VersionInfo,
        SelectCatalogCode
    },
    setup() {
        const instance: any = getCurrentInstance();
        const route = useRoute();
        const versionTreeRef = ref<any>();
        const state = reactive<any>({
            loading: false,
            checkedLine: -1,
            checkedPro: -1,
            checkedSubPro: -1,
            lineOptions: [],
            proOptions: [],
            subProOptions: [],
            isEmpty: false,
            selectedVersionInfo: {},
            systemDetail: {},
            productManager: [],
            leftWidth: '350px',
            isCollaspeHeader: false,
            treeData: null,
            catalogCode: ''
        });
        // 获取当前选中系统信息
        const systemInfo = computed(() => {
            if (!state.subProOptions.length && !state.proOptions.length) {
                return '';
            } else {
                // 选中子级就是子级
                if (state.checkedSubPro > -1 && state.subProOptions.length) {
                    return state.subProOptions[state.checkedSubPro];
                }
                // 不然就是父级
                else {
                    return state.proOptions[state.checkedPro];
                }
            }
        });
        // 产品节点
        const proSystemInfo = computed(() => {
            if (state.checkedPro >= 0) {
                if (state.proOptions && state.proOptions.length) {
                    return state.proOptions[state.checkedPro];
                } else {
                    return {};
                }
            } else {
                return {};
            }
        });
        const collaspeHeaderTitle = computed(() => {
            let str = '';
            if (state.lineOptions.length && state.checkedLine >= 0) {
                str = state.lineOptions[state.checkedLine].catalogName;
                if (state.proOptions.length && state.checkedPro >= 0) {
                    str += ` / ${state.proOptions[state.checkedPro].catalogName}`;
                    if (state.subProOptions.length && state.checkedSubPro >= 0) {
                        str += ` / ${state.subProOptions[state.checkedSubPro].catalogName}`;
                    }
                }
            }
            return str;
        });
        // 所有操作限制
        const disabled = computed(() => {
            // 系统的负责人才能编辑
            if (state.productManager && state.productManager.length) {
                return !state.productManager.includes(store.getters.userInfo.employeeDTO.name);
            } else {
                return true;
            }
        });
        // 获取子产品或产品
        const getAllProItem = (treeData, level) => {
            const arr: any = [];
            const getItem = (data) => {
                data.forEach((item) => {
                    if (+item.node.catalogType <= level - 1) {
                        if (item.subNodes && item.subNodes.length) {
                            getItem(item.subNodes);
                        }
                    } else {
                        if (item.node.catalogType == level) {
                            arr.push({
                                id: item.id,
                                ...item.node,
                                node: item.node,
                                subNodes: item.subNodes || []
                            });
                        }
                    }
                });
            };
            getItem(treeData);
            return arr;
        };
        // 获取子产品选项
        const getSubProOptions = (treeData) => {
            state.subProOptions = getAllProItem(treeData, 2);
            state.checkedSubPro = -1;
        };
        // 获取产品选项
        const getProOptions = (treeData) => {
            state.proOptions = getAllProItem(treeData, 1);
            if (state.proOptions.length) {
                state.checkedPro = 0;
                getSubProOptions([state.proOptions[0]]);
            } else {
                state.checkedPro = -1;
            }
        };
        const handleChangeLine = (val, index) => {
            if (val) {
                state.checkedLine = index;
                getProOptions([state.treeData[index]]);
            }
        };
        const handleChangePro = (val, index) => {
            if (val) {
                state.checkedPro = index;
                getSubProOptions([state.proOptions[index]]);
            }
        };
        const handleChangeSubPro = (val, index) => {
            if (val) {
                state.checkedSubPro = index;
            } else {
                state.checkedSubPro = -1;
            }
        };
        const handleSelectTree = (val) => {
            state.selectedVersionInfo = val;
        };

        const handleSuccess = (type) => {
            if (type === 'delete') {
                state.selectedVersionInfo = {};
            }
            unref(versionTreeRef).getList();
        };

        const getSystemDetail = async () => {
            const query = {
                catalogCode: systemInfo.value.catalogCode
            };
            const { success, moule } = await api.productDetailModel.findByCatalogCode(query);
            if (success) {
                state.systemDetail = {
                    ...moule
                };
            }
        };

        const getPosition = async () => {
            const { success, moule } = await api.texingTreeModel.getBySystemIdAndPosition({
                catalogCode: systemInfo.value.catalogCode,
                position: '产品经理'
            });
            if (success) {
                if (moule && moule.length) {
                    state.productManager = moule.map((item) => item.empName);
                } else {
                    state.productManager = [];
                }
            }
        };
        const handleToggleCollaspeHeader = () => {
            state.isCollaspeHeader = !state.isCollaspeHeader;
        };

        const handleCascaderChange = (val) => {
            const { nodeInfo } = val;
            initOptions(nodeInfo.catalogCode, nodeInfo.catalogType);
        };
        const init = async () => {
            state.isEmpty = false;
            const query = {
                type: 3
            };
            const { success, moule } = await api.portalControlModel.getSystemProductCatalogTreeData(query);
            if (success) {
                if (moule) {
                    state.treeData = JSON.parse(moule);
                    state.lineOptions = state.treeData.map((item) => ({
                        id: item.id,
                        ...item.node
                    }));

                    console.log('产品线', state.lineOptions);
                    // 获取产品选项
                    if (state.lineOptions.length) {
                        initOptions(route.query.catalogCode, route.query.catalogType);
                    }
                } else {
                    state.isEmpty = true;
                }
            }
        };
        const initOptions = async (catalogCode, catalogType) => {
            // 看是否有默认值，有默认值说明从外部过来新建的
            if (catalogCode && catalogType) {
                const target: any = treeFilter(state.treeData, (node) => node.node.catalogCode === catalogCode);
                console.log('target', target);
                if (target && target.length) {
                    const lineIndex = state.treeData.findIndex((item) => item.node.catalogCode === target[0].node.catalogCode);
                    state.checkedLine = lineIndex;
                    state.proOptions = getAllProItem([state.treeData[lineIndex]], 1);
                    const proIndex = state.proOptions.findIndex((item) => item.node.catalogCode === target[0].subNodes[0].node.catalogCode);
                    state.checkedPro = proIndex;
                    state.subProOptions = getAllProItem([state.proOptions[proIndex]], 2);
                    if (catalogType === '2' && state.subProOptions.length) {
                        const subProIndex = state.subProOptions.findIndex(
                            (item) => item.node.catalogCode === target[0].subNodes[0].subNodes[0].node.catalogCode
                        );
                        state.checkedSubPro = subProIndex;
                    } else {
                        state.checkedSubPro = -1;
                    }
                } else {
                    getProOptions([state.treeData[0]]);
                    state.checkedLine = 0;
                }
            } else {
                getProOptions([state.treeData[0]]);
                state.checkedLine = 0;
            }
        };
        const updateWidth = (val) => {
            state.leftWidth = val;
        };
        init();
        window.onresize = () => {
            state.leftWidth = '350px';
        };

        onMounted(() => {
            instance.proxy.$mitt.on('reloadPage', () => {
                nextTick(() => {
                    unref(versionTreeRef).getList();
                });
            });
        });

        watch(
            () => systemInfo.value,
            () => {
                if (state.selectedVersionInfo) {
                    state.selectedVersionInfo = {};
                }
                state.leftWidth = '350px';
                getPosition();
                getSystemDetail();
                state.catalogCode = systemInfo.value.catalogCode;
            }
        );
        return {
            versionTreeRef,
            ...toRefs(state),
            collaspeHeaderTitle,
            systemInfo,
            proSystemInfo,
            disabled,
            handleChangeLine,
            handleChangePro,
            handleChangeSubPro,
            handleSelectTree,
            handleSuccess,
            updateWidth,
            handleToggleCollaspeHeader,
            handleCascaderChange,
            getSystemDetail
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        height: calc(100vh - 64px);
        overflow: hidden;
        .left {
            padding: 12px 12px 0 0;
            height: 100%;
            position: relative;
            border-right: 1px solid #e8eaec;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        .page-header {
            background: #fff;
            padding: 24px;
            position: relative;
        }
        display: flex;
        flex-direction: column;
    }
    /* 拖动条 */
    .moveBtn {
        height: 100%;
        width: 6px;
        position: absolute;
        right: 0px;
        top: 0;
        cursor: col-resize;
    }

    ::-webkit-scrollbar {
        width: 0px;
        height: 6px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #9093994d;
        border-radius: 2px;
        box-shadow: inset 0 0 6px #0003;
    }
    // 轨道样式
    ::-webkit-scrollbar-track {
        background-color: #0000000d;
    }
}
</style>